package ar.republicagroup.gestion.view;
import ar.republicagroup.gestion.entities.Cheque;
import ar.republicagroup.gestion.entities.Cliente;
import ar.republicagroup.gestion.entities.ClienteSaldo;
import ar.republicagroup.gestion.entities.Liquidacion;
import ar.republicagroup.gestion.entities.Usuario;
import ar.republicagroup.gestion.services.ChequeEstadoServices;
import ar.republicagroup.gestion.services.ChequeServices;
import ar.republicagroup.gestion.services.ClienteSaldoServices;
import ar.republicagroup.gestion.services.ExportarServices;
import ar.republicagroup.gestion.services.LiquidacionServices;
import ar.republicagroup.gestion.util.AppSession;
import ar.republicagroup.gestion.util.SpringUtils;
import ar.republicagroup.gestion.util.TableColumnAdjuster;
import ar.republicagroup.gestion.util.UserSession;
import ar.republicagroup.gestion.util.Validar;
import ar.republicagroup.gestion.util.exportar.ReportModel;
import ar.republicagroup.gestion.util.helpers.Formato;
import ar.republicagroup.gestion.util.messages.UIMessages;
import java.awt.Color;
import java.awt.Toolkit;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import javax.swing.table.DefaultTableModel;
import org.apache.log4j.Logger;

public class modalPanelAddLiquidacion extends javax.swing.JDialog {

    private Vector<Vector> data = new Vector<>();
    private String nombre_cliente;
    private Cliente cliente;
    private ClienteSaldo clienteSaldo;
    boolean liquidacionOk             = false;
    boolean progress                  = true;
    private boolean isLastLiquidPaid  = false;
    Date fechaLiquidacion; 
    
    double saldoActualDespuesDelPago;
    
    
  
  /*Services*/
    ExportarServices exportarServices                   = (ExportarServices)SpringUtils.getBean("exportarServices");
    LiquidacionServices liquidacionServices             = (LiquidacionServices)SpringUtils.getBean("liquidacionServices");
    ChequeServices chequesServices                      = (ChequeServices)SpringUtils.getBean("chequeServices");
    ClienteSaldoServices clienteSaldoServices           = (ClienteSaldoServices)SpringUtils.getBean("clienteSaldoServices");
    ChequeEstadoServices chequeEstadoServices           = (ChequeEstadoServices)SpringUtils.getBean("chequeEstadoServices");
    
    /* Logging */
    Logger log =  Logger.getLogger(modalPanelAddLiquidacion.class);    
    private List<Cheque> chequeList;
    
    
    private Task task;
    
    Map<String,Object> mapClienteLiquidacionImporte = new HashMap();
    
    

    public modalPanelAddLiquidacion(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents(); 
        valoresPorDefecto();
    }

    public Cliente getCliente() {
        return cliente;
    }

    public void setCliente(Cliente cliente) {
        this.cliente = cliente;
    }

    public List<Cheque> getChequeList() {
        return chequeList;
    }

    public void setChequeList(List<Cheque> chequeList) {
        this.chequeList = chequeList;
    }

    public String getNombre_cliente() {
        return nombre_cliente;
    }

    public void setNombre_cliente(String nombre_cliente) {
        this.nombre_cliente = nombre_cliente;
    }

    public ClienteSaldo getClienteSaldo() {
        return clienteSaldo;
    }

    public void setClienteSaldo(ClienteSaldo clienteSaldo) {
        this.clienteSaldo = clienteSaldo;
    }

    public Date getFechaLiquidacion() {
        return fechaLiquidacion;
    }

    public void setFechaLiquidacion(Date fechaLiquidacion) {
        this.fechaLiquidacion = fechaLiquidacion;
    }
    
    
    

    
    private void cargarTablaLiquidacion(List<Cheque> listado){
        DefaultTableModel model = (DefaultTableModel) tblCheque.getModel();
        model.getDataVector().clear();
        
       
        for(Cheque cheque:listado){
            model.addRow(new Object[]{cheque.getChequeNro(),cheque.getOrigen(),Formato.decimalComaMilesConSigno(cheque.getImporte().doubleValue()),cheque.getComision(),cheque.getChequeEstadoId().getNombre()});
            if(getCliente().getComisionRechazo().equals("N")){
                cheque.setGestionEnRechazos("N");
            }else{
                cheque.setGestionEnRechazos("Y");
            }
            liquidacionServices.addChequeToLiquidacion(cheque);
        }
        
        TableColumnAdjuster tca = new TableColumnAdjuster(tblCheque);
        tca.adjustColumns();
        tblCheque.setAutoCreateRowSorter(true);
        tblCheque.setModel(model);
        tblCheque.repaint();
              
    }
    
   
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblCheque = new javax.swing.JTable();
        btnLiquidacion = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        txtTotalVC = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        txtTotalChequesRechazados = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txtTotalRechazo1 = new javax.swing.JTextField();
        txtTotalLiquid = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        txtTotalRechazo2 = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        lblCliente = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        txtTotalCAP = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        txtNotas = new javax.swing.JTextArea();
        jLabel10 = new javax.swing.JLabel();
        txtLiquidacionAnterior = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("...: Liquidación de cheques :...");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Confirme liquidación"));

        tblCheque.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Nro.Cheque", "Origen", "Importe", "Comisión", "Estado"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tblCheque);

        btnLiquidacion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/check.png"))); // NOI18N
        btnLiquidacion.setText("Es correcto, liquidar!");
        btnLiquidacion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLiquidacionActionPerformed(evt);
            }
        });

        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/cancel.png"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        txtTotalVC.setEditable(false);

        jLabel1.setText("VC");

        txtTotalChequesRechazados.setEditable(false);

        jLabel2.setText("Cheques rechazados");

        jLabel3.setText("Rechazo 1");

        txtTotalRechazo1.setEditable(false);

        txtTotalLiquid.setEditable(false);

        jLabel4.setText("Total Liquidación");

        txtTotalRechazo2.setEditable(false);

        jLabel5.setText("Rechazo 2");

        jLabel6.setText("Liquidación cliente :");

        lblCliente.setText("nombre_cliente");

        jLabel7.setText("Notas");

        txtTotalCAP.setEditable(false);

        jLabel9.setText("CAP");

        txtNotas.setColumns(20);
        txtNotas.setRows(5);
        txtNotas.setAutoscrolls(false);
        jScrollPane2.setViewportView(txtNotas);

        jLabel10.setText("Liquid. Anterior");

        txtLiquidacionAnterior.setEnabled(false);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel6)
                                .addGap(18, 18, 18)
                                .addComponent(lblCliente))
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(btnLiquidacion))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(23, 23, 23)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel5)
                                    .addComponent(jLabel4)
                                    .addComponent(jLabel1)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel9))
                                .addGap(31, 31, 31)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtTotalCAP, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addComponent(txtTotalVC, javax.swing.GroupLayout.DEFAULT_SIZE, 118, Short.MAX_VALUE)
                                        .addComponent(txtTotalRechazo2)
                                        .addComponent(txtTotalChequesRechazados)
                                        .addComponent(txtTotalRechazo1)
                                        .addComponent(txtTotalLiquid)))
                                .addGap(0, 0, Short.MAX_VALUE)))
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                        .addComponent(jLabel7)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                        .addComponent(jLabel10)
                                        .addGap(18, 18, 18)
                                        .addComponent(txtLiquidacionAnterior, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(38, 38, 38))))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(33, 33, 33)
                                .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE)))))
                .addGap(43, 43, 43))
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnCancelar, btnLiquidacion});

        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(17, 17, 17)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(lblCliente))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(27, 27, 27)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtTotalVC, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel10)
                    .addComponent(txtLiquidacionAnterior, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel9)
                            .addComponent(txtTotalCAP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel7))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, 12, Short.MAX_VALUE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtTotalChequesRechazados, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtTotalRechazo1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtTotalRechazo2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel5))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtTotalLiquid, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel4))
                        .addGap(32, 32, 32)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(btnCancelar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnLiquidacion, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addGap(18, 18, 18))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnLiquidacionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLiquidacionActionPerformed
        int respuestaConfirma = JOptionPane.showConfirmDialog(this,"¿Confirma la liquidación?" , UIMessages.getQuestionMessage("defaultQuestionTitle"), JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE); 
            if(respuestaConfirma == JOptionPane.OK_OPTION){
                Liquidacion ultimaLiquidacion = liquidacionServices.getLastLiquidacionByCliente(getCliente());
                if(ultimaLiquidacion != null){
                    if(ultimaLiquidacion.getImportePagado() == 0 && ultimaLiquidacion.getPosponer_pago().equals("N")){
                        int respuesta = JOptionPane.showConfirmDialog(this, UIMessages.getQuestionMessage("confirm_pago_liquidacion_anterior"), 
                                            UIMessages.getQuestionMessage("defaultQuestionTitle"), 
                                            JOptionPane.YES_NO_OPTION);
            
                        if (respuesta == JOptionPane.YES_OPTION){
                            log.info("saldo actual antes del pago : "+clienteSaldo.getSaldoActual());
                            modalPanelAddPago panel = new modalPanelAddPago(null, true);
                            panel.setLiquidacion(ultimaLiquidacion);
                            panel.setClienteSaldo(getClienteSaldo());
                            panel.setIsOpenFromAnotherParent(true);
                            panel.setLocationRelativeTo(this);
                            panel.setVisible(true);
                            isLastLiquidPaid = panel.isLiquidPaid();
                            log.info("saldo actual después del pago :"+clienteSaldo.getSaldoActual());
                            saldoActualDespuesDelPago = clienteSaldo.getSaldoActual();
                            
                            if(!isLastLiquidPaid){
                                ultimaLiquidacion.setPosponer_pago("Y");
                                liquidacionServices.update(ultimaLiquidacion);
                            }
                            
                            
                        }else {
                            ultimaLiquidacion.setPosponer_pago("Y");
                            liquidacionServices.update(ultimaLiquidacion);
                        }
                        
                    }else{
                        saldoActualDespuesDelPago = clienteSaldo.getSaldoActual();
                        isLastLiquidPaid = true;
                    }
                }
                
                mostrarBarraDeProgresoEIniciarTask();
            }
             
    }//GEN-LAST:event_btnLiquidacionActionPerformed

    
    public void mostrarBarraDeProgresoEIniciarTask(){
            final BarraDeProgreso barra;
            barra = new BarraDeProgreso(this, false);
            barra.setLocationRelativeTo(this);
            barra.setVisible(true);
            task = new Task();
            task.addPropertyChangeListener(new PropertyChangeListener() {

             @Override
             public void propertyChange(PropertyChangeEvent pcEvt) {
                if (SwingWorker.StateValue.DONE == pcEvt.getNewValue()) {
                   Toolkit.getDefaultToolkit().beep(); 
                   barra.setVisible(false);
                   barra.dispose();            
                }
             }
          });
       
            task.execute();
    }
    
    
     /* CLASE INNER */    
    class Task extends SwingWorker<Void, Void> {
        
        @Override
        public Void doInBackground() throws Exception {
             liquidar();
             return null;
        }

      
    }
    
   
    public void liquidar(){
        
        boolean errorAlReportar = false;
        double totalLiquidacion         =  0;
        double subTotalLiquidacion      = Double.parseDouble(Formato.decimalSoloPunto(txtTotalLiquid.getText()));
        
         /* Seteando los datos de la liquidación */
         Liquidacion liquidacion = new Liquidacion();
         liquidacion.setFechaRegistro(new Date());
         liquidacion.setFechaLiquidacion(getFechaLiquidacion());
         liquidacion.setImportePagado(0);
         
         if(subTotalLiquidacion > 0){
            liquidacion.setPosponer_pago("N");
         }else{
            liquidacion.setPosponer_pago("Y");
         }
         
         liquidacion.setClienteId(getCliente());
         liquidacion.setTotalLiquidacion(subTotalLiquidacion);
         liquidacion.setNota(txtNotas.getText());
         liquidacion.setUsuarioId(new Usuario(UserSession.getInstance().getUser_id()));
         liquidacion.setLiquidacionDetalleList(liquidacionServices.convertirChequesAListDeDetalle(chequeList, liquidacion));
         liquidacion.setEstado(1);
         
            if(clienteSaldo == null){
                clienteSaldo = new ClienteSaldo();
            }
            clienteSaldo.setClienteId(getCliente());
            clienteSaldo.setLiquidacionId(liquidacion);
            
            
            
           
            if(isLastLiquidPaid){
                    clienteSaldo.setSaldoAnterior(saldoActualDespuesDelPago);
                    
                    if(subTotalLiquidacion > 0){
                        totalLiquidacion = subTotalLiquidacion + clienteSaldo.getSaldoActual()*(-1);
                        clienteSaldo.setSaldoActual( subTotalLiquidacion + clienteSaldo.getSaldoActual()*(-1));
                    }else{
                        totalLiquidacion = Math.abs(subTotalLiquidacion) + clienteSaldo.getSaldoActual();
                        clienteSaldo.setSaldoActual( Math.abs(subTotalLiquidacion) + clienteSaldo.getSaldoActual());
                    }
                    
                    liquidacion.setSaldoCliente(clienteSaldo.getSaldoAnterior());
            } else {
                    clienteSaldo.setSaldoAnterior(Double.parseDouble(txtLiquidacionAnterior.getText()));
                
                if( clienteSaldo.getSaldoActual() >= 0 ){
                    totalLiquidacion = subTotalLiquidacion + clienteSaldo.getSaldoActual();
                    clienteSaldo.setSaldoActual( Math.abs(subTotalLiquidacion) + clienteSaldo.getSaldoActual() );
                    liquidacion.setSaldoCliente(clienteSaldo.getSaldoAnterior()*(-1));
                } else {
                    
                        if(subTotalLiquidacion > 0){
                             totalLiquidacion = (subTotalLiquidacion + clienteSaldo.getSaldoActual()*(-1));
                        }else{
                             totalLiquidacion = (subTotalLiquidacion + clienteSaldo.getSaldoActual());
                        }
                        
                        clienteSaldo.setSaldoActual(totalLiquidacion);
                        liquidacion.setSaldoCliente(clienteSaldo.getSaldoAnterior());
                }
            
            }
            
            clienteSaldo.setEstado(1);
         
         
         List<ClienteSaldo> clienteSaldoList = new ArrayList<>();
         clienteSaldoList.add(clienteSaldo);
         liquidacion.setClienteSaldoList(clienteSaldoList);
         
         
         
         /* Parametros para enviar al reporte PDF */
         Map parametros = new HashMap();
         parametros.put("fecha", Formato.cambiarFechaAFormatoLocal(new Date()));
         parametros.put("cliente",getCliente().getNombre());
         parametros.put("valores_al_cobro_prov",Formato.decimalComaMiles(liquidacionServices.getTotalValoresAlCobroVC() + liquidacionServices.getTotalRechazosVC()));
         parametros.put("valores_al_cobro_cap",Formato.decimalComaMiles(liquidacionServices.getTotalValoresAlCobroCAP()+ liquidacionServices.getTotalRechazosCAP()));
         parametros.put("com_gestion",Formato.decimalComaMiles(liquidacionServices.getTotalComGestion()));
         parametros.put("com_cap",liquidacionServices.getComisionCAP());
         parametros.put("com_vc",liquidacionServices.getComisionVC());
         parametros.put("subtotal_cap",Formato.decimalComaMiles(liquidacionServices.getSubtotalCAP()));
         parametros.put("subtotal_vc",Formato.decimalComaMiles(liquidacionServices.getSubtotalVC()));
         parametros.put("total_rechazado",liquidacionServices.getTotalRechazados());
         parametros.put("subtotal_gestion",Formato.decimalComaMiles(liquidacionServices.getSubtotalGestion()));
         parametros.put("total_gestion", Formato.decimalComaMiles(liquidacionServices.getTotalLiquidacion())); 
         
         if(isLastLiquidPaid){
             parametros.put("liquid_anterior", Formato.decimalComaMiles(saldoActualDespuesDelPago));
         }else{
             parametros.put("liquid_anterior",Formato.decimalComaMiles(clienteSaldo.getSaldoAnterior()));
         }
         
         if(subTotalLiquidacion > 0){
            parametros.put("saldo",Formato.decimalComaMiles(totalLiquidacion));
         }else{
            parametros.put("saldo","0");
         }
         
         parametros.put("notas",txtNotas.getText());
         
         
         
               try {
                    liquidacionServices.insert(liquidacion);
                    /* Actualizamos el estado de los cheques que fueron liquidados*/
                    for(Cheque cheque : chequeList){
                        chequesServices.update(cheque);
                    }
                    
                    exportarServices.reporteDeLiquidacionesToPDF(ReportModel.reporteDeLiquidacion(chequeList), parametros);
                } catch (Exception ex) {
                    log.info("No se pudo generar el reporte de liquidaciones a PDF");
                    log.error("Error al generar reporte "+ex.getMessage(),ex);
                    errorAlReportar = true;
                }
         
                if(!errorAlReportar){
                    JOptionPane.showMessageDialog(this, UIMessages.getInfoMessage("onCompleteExport"), UIMessages.getInfoMessage("onCompleteExport_title"), JOptionPane.INFORMATION_MESSAGE);
                    liquidacionOk = true;
                    liquidacionServices.reiniciarTotales();
                    progress = false;
                    dispose();
                    frmLiquidacion.btnBuscar.doClick();
                    frmMain.btnActualizar.doClick();
                    
//                    frmLiquidacion.getInstance().getClientesToLiquid();
//                    mapClienteLiquidacionImporte = chequesServices.getLiquidacionesPosiblesPorCadaCliente(AppSession.getFechaDeLiquidacion());
//                    frmLiquidacion.getInstance().setClientesToLiquid(mapClienteLiquidacionImporte.keySet());
//                    //REVISAR ESTO
//                    frmLiquidacion.getInstance().actualizarComboDeClientes();
                    
                } else {
                    JOptionPane.showMessageDialog(this, UIMessages.getErrorMessage("onExportError"), UIMessages.getErrorMessage("defaultErrorTitle"),JOptionPane.ERROR_MESSAGE);
                    progress = false;
                } 

    }

  
    
    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        lblCliente.setText(getCliente().getNombre());
        cargarTablaLiquidacion(getChequeList());
        clienteSaldo = clienteSaldoServices.getSaldoActualByCliente(getCliente());
        liquidacionServices.setCliente(getCliente());
        setearTotalesDeLiquidacion();
        
    }//GEN-LAST:event_formWindowOpened

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
       dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
       if(!liquidacionOk){
          frmLiquidacion.setChequeList(chequeList);
          frmLiquidacion.cargarTablaCheque(frmLiquidacion.getChequeList());
          liquidacionServices.reiniciarTotales();
          }
    }//GEN-LAST:event_formWindowClosed

  

    private void valoresPorDefecto(){
       
    }
    
    
    public void setearTotalesDeLiquidacion(){
        txtTotalCAP.setText(Formato.decimalComaMilesConSigno(liquidacionServices.getTotalValoresAlCobroCAP() + liquidacionServices.getTotalRechazosCAP()));
        txtTotalVC.setText(Formato.decimalComaMilesConSigno(liquidacionServices.getTotalValoresAlCobroVC() + liquidacionServices.getTotalRechazosVC()));
        txtTotalChequesRechazados.setText(Formato.decimalComaMilesConSigno(liquidacionServices.getTotalRechazos()));
        txtTotalRechazo1.setText(Formato.decimalComaMilesConSigno(liquidacionServices.getTotalRechazo1()));
        txtTotalRechazo2.setText(Formato.decimalComaMilesConSigno(liquidacionServices.getTotalRechazo2()));
        
        if(clienteSaldo != null){
            txtLiquidacionAnterior.setText(""+Validar.redondearDoubleADosDecimales(getClienteSaldo().getSaldoActual()));
            if(getClienteSaldo().getSaldoActual() > 0){
                txtLiquidacionAnterior.setForeground(Color.BLUE);
            }else{
                txtLiquidacionAnterior.setForeground(Color.RED);
            }
        }else{
            txtLiquidacionAnterior.setText("0");
        }
        txtTotalLiquid.setText(String.valueOf(Formato.decimalComaMilesConSigno(liquidacionServices.getTotalLiquidacion())));
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                modalPanelAddLiquidacion dialog = new modalPanelAddLiquidacion(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnLiquidacion;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lblCliente;
    private javax.swing.JTable tblCheque;
    private javax.swing.JTextField txtLiquidacionAnterior;
    private javax.swing.JTextArea txtNotas;
    private javax.swing.JTextField txtTotalCAP;
    private javax.swing.JTextField txtTotalChequesRechazados;
    private javax.swing.JTextField txtTotalLiquid;
    private javax.swing.JTextField txtTotalRechazo1;
    private javax.swing.JTextField txtTotalRechazo2;
    private javax.swing.JTextField txtTotalVC;
    // End of variables declaration//GEN-END:variables
}
